const db = require('../config/db');
const jwt = require('jsonwebtoken');
const secretKey = 'my_secret_key';
// 获取所有订单
exports.getOrders = (req, res) => {
    db.query('SELECT * FROM order1', (err, results) => {
        if (err) {
            res.status(500).json({ error: '从数据库获取订单时出错' });
            return;
        }
        res.json(results);
    });
};

// 根据ID获取订单
exports.getOrderById = (req, res) => {
    const keyword = req.query.keyword;
    const query = `SELECT * FROM order1 WHERE order_id LIKE ? OR name LIKE ? OR order_pay LIKE ? OR order_status LIKE ?`;
    const searchKeyword = `%${keyword}%`;
    if (req.query.keyword === '') {
        res.status(400).json({ message: '请输入搜索关键字' });
    } else {
        db.query(query, [searchKeyword,searchKeyword,searchKeyword,searchKeyword], (error, results) => {
            if (error) {
                res.status(500).json({ error: 'Error' });
                return;
            }
            res.json(results);
        });
    }
};

// 删除订单
exports.deleteOrder = (req, res) => {
    const { id } = req.params;
    const sqlDelete = 'DELETE FROM os_orders WHERE order_id = ?';
    db.query(sqlDelete, [id], (err, results) => {
        if (err) {
            res.status(500).json({ message: '删除订单失败' });
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '订单删除成功' });
        } else {
            res.status(404).json({ message: '未找到订单', orderId: id });
        }
    });
};

exports.createOrder = (req, res) => {
    const {orderMoney,orderPay,orderNote} = req.query.data;
    const orderId = Date.now() + Math.floor(Math.random() * 1000); // 生成时间戳+随机数的唯一订单ID
    const orderTime = new Date().toLocaleString();
    const orderStatus = '待支付';
    
    const authHeader = req.headers.authorization;
    let userId;
    if (authHeader) {
        const token = authHeader.split(' ')[1];
        const decoded = jwt.verify(token, secretKey);
        userId = decoded.userId;
    }
    const sqlCreate = 'INSERT INTO os_orders (order_id, order_time, user_id, order_money, order_pay,order_status,order_note) VALUES (?, ?, ?, ?, ?, ?, ?)';
    db.query(sqlCreate, [orderId, orderTime, userId, orderMoney, orderPay, orderStatus, orderNote], (err, results) => {
        if (err) {
            res.status(500).json({ message: '创建订单失败' });
            console.log(err);
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '订单创建成功', orderId: orderId });
        } else {
            res.status(400).json({ message: '订单创建失败' });
        }
    });
}

exports.createOrderDetail = (req, res) => {
    const { orderId, cartItems } = req.query.data;
    let successCount = 0;
    let totalItems = cartItems.length;
    cartItems.forEach(item => {
        const sqlCreate = 'INSERT INTO os_orders_items (order_id, book_id, book_num) VALUES (?, ?, ?)';
        db.query(sqlCreate, [orderId, item.id, item.quantity], (err, results) => {
            if (err) {
                console.log(err);
                return res.status(500).send({ message: '创建订单详情失败' });
            }
            successCount++;
            // 当所有项目都处理完成时返回响应
            if (successCount === totalItems) {
                res.status(200).send({ message: '订单详情创建成功' });
            }
        });
    });
}

exports.updateOrderStatus = (req, res) => {
    const orderId = req.params.orderId;
    const { status } = req.body;
    const sqlUpdate = 'UPDATE os_orders SET order_status = ? WHERE order_id = ?';
    db.query(sqlUpdate, [status, orderId], (err, results) => {
        if (err) {
            console.log(err);
            return res.status(500).send({ message: '更新订单状态失败' });
        }
        if (results.affectedRows === 0) {
            return res.status(404).send({ message: '订单未找到' });
        }
        res.status(200).send({ message: '订单状态更新成功' });
    });
};

exports.getOrder = (req, res) => {
    const authHeader = req.headers.authorization;
    let userId;
    if (authHeader) {
        const token = authHeader.split(' ')[1];
        const decoded = jwt.verify(token, secretKey);
        userId = decoded.userId;
    }
    const sqlGet = 'SELECT * FROM os_orders WHERE user_id = ?';
    db.query(sqlGet, [userId], (err, results) => {
        if (err) {
            res.status(500).json({ message: '获取订单失败' });
            return;
        }
        res.json(results);
    });
}

exports.getOrderDetail = (req, res) => {
    const { orderId } = req.query;
    const sqlGet = 'SELECT * FROM order_detail WHERE order_id = ?';
    db.query(sqlGet, [orderId], (err, results) => {
        if (err) {
            res.status(500).json({ message: '获取订单详情失败' });
            console.log(err);
            return;
        }
        res.json(results);
    });
}

exports.payOrder = (req, res) => {
    const {orderId,orderPay} = req.query.data;
    const orderStatus = '待发货';
    const sqlUpdate = 'UPDATE os_orders SET order_status = ?,order_pay = ? WHERE order_id = ?';
    db.query(sqlUpdate, [orderStatus, orderPay, orderId], (err, results) => {
        if (err) {
            res.status(500).json({ message: '支付订单失败' });
            console.log(err);
            return;
        }
        if (results.affectedRows > 0) {
            res.status(200).json({ message: '支付成功' });
        } else {
            res.status(400).json({ message: '支付失败' });
        }
    });
}

